package p.ithorns.tools.log;

import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;

/**
 * <p>
 * UUID工具类
 * </p>
 *
 * @author ithorns
 */
final class UUIDUtil {

    /**
     * <p>
     * 获取去除“-”的UUID
     * </p>
     *
     * @return 不带“-”的UUID
     */
    public static String getUUID() {
        UUID uuid = UUID.randomUUID();
        String str = uuid.toString();
        // 去掉"-"符号
        return str.substring(0, 8) + str.substring(9, 13) + str.substring(14, 18)
                + str.substring(19, 23) + str.substring(24);
    }

    /**
     * <p>
     * 获得指定数量的UUID
     * </p>
     *
     * @param number UUID数量
     * @return UUID数组
     */
    public static String[] getUUID(int number) {
        if (number < 1) {
            return null;
        }
        String[] ss = new String[number];
        for (int i = 0; i < number; i++) {
            ss[i] = getUUID();
        }
        return ss;
    }

    /**
     * <p>
     * 获得指定数量的UUID
     * </p>
     *
     * @param number UUID数量
     * @return UUID数组
     */
    public static String uuid(String feed) {
        return uuid(feed, 32);
    }


    public static String uuid(String feed, int len) {
        if (!StringUtils.hasText(feed)) {
            feed = UUID.randomUUID().toString();
        }
        String uuid = DigestUtils.md5DigestAsHex(feed.getBytes()) + Math.abs(feed.hashCode());
        char[] chars = uuid.toCharArray();
        StringBuilder sb = new StringBuilder();

        int charlen = chars.length - 1;
        for (int i = 0; i < len; i++) {
            sb.append(chars[ThreadLocalRandom.current().nextInt(charlen)]);
        }
        return sb.toString();
    }

}